package com.cdk8s.example.simplespringboot.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 关于异常的工具类.
 */
@Slf4j
public final class ExceptionUtil {

	/**
	 * 在request中获取异常类
	 *
	 * @param request
	 * @return
	 */
	public static Throwable getThrowable(HttpServletRequest request) {
		Throwable ex = null;
		if (request.getAttribute("exception") != null) {
			ex = (Throwable) request.getAttribute("exception");
		} else if (request.getAttribute("javax.servlet.error.exception") != null) {
			ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
		}
		return ex;
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getStackTraceAsString(Throwable e) {
		if (e == null) {
			return "";
		}
		return ExceptionUtils.getStackTrace(e);
	}

	public static void printStackTraceAsString(Throwable e) {
		if (e == null) {
			return;
		}
		log.error("------zch------错误信息 <{}>", ExceptionUtils.getStackTrace(e));
	}

	/**
	 * 将ErrorStack转化为String.
	 */
	public static String getRootCauseStackTraceAsString(Throwable e) {
		if (e == null) {
			return "";
		}

		String[] rootCauseStackTrace = ExceptionUtils.getRootCauseStackTrace(e);
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("\n");
		if (rootCauseStackTrace.length < 5) {
			for (int i = 0; i < rootCauseStackTrace.length; i++) {
				stringBuilder.append(rootCauseStackTrace[i]);
				stringBuilder.append("\n");
			}
			return stringBuilder.toString();
		} else {
			for (int i = 0; i < 5; i++) {
				stringBuilder.append(rootCauseStackTrace[i]);
				stringBuilder.append("\n");
			}
			return stringBuilder.toString();
		}
	}

	/**
	 * 判断异常是否由某些底层的异常引起.
	 */
	@SuppressWarnings("unchecked")
	public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex.getCause();
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}

	/**
	 * 将CheckedException转换为UncheckedException.
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

}
